package com.study.kafka.custom.serialization;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 消费者
 *
 * @author: stephen.shen
 * @create: 2019-06-18 11:47
 */
public class DemoKafkaConsumer {

    private final static String brokerList = "localhost:9092";
    private final static String topic = "test-topic";
    private final static String groupId = "group-test";
    private final static AtomicBoolean isRunning = new AtomicBoolean(true);

    private static Properties initConfig() {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                DemoDeserializer.class.getName());
        return props;
    }

    public static void main(String[] args) {
        Properties props = initConfig();
        KafkaConsumer<String, Person> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(topic));

        try {
            while (isRunning.get()) {
                ConsumerRecords<String, Person> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, Person> record : records) {
                    System.out.println("key = " + record.key() + ", value = " + record.value()
                            + ", topic = " + record.topic() + ", partition = " + record.partition()
                            + ", offset = " + record.offset());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            consumer.close();
        }
    }
}
